#include "AnimatedSprite.h"

using namespace std;
using namespace me;

AnimatedSprite::AnimatedSprite(): m_currentAnimation(NULL), m_frozen(false)
{

}

AnimatedSprite::~AnimatedSprite()
{

}

void AnimatedSprite::update()
{
    if ( (m_currentAnimation != NULL) && (!m_frozen) && (m_currentTime.getElapsedTime() >= m_frameTime) )
    {
        m_currentFrame++;
        if (m_currentFrame == m_currentAnimation->getSize())
            m_currentFrame = 0;

        setTextureRect(m_currentAnimation->getFrame(m_currentFrame));
        m_currentTime.restart();
    }
}

bool AnimatedSprite::addAnimation(me::Animation animation)
{
    string name = animation.getName();
    for (unsigned int i=0 ; i < m_animations.size() ; i++)
    {
        if (name == m_animations[i].getName())
            return false;
    }
    if (animation.getTexture() == NULL)
        return false;

    if (animation.getSize() == 0)
        return false;

    m_animations.push_back(animation);
    return true;
}

bool AnimatedSprite::removeAnimation(string name)
{
    for (unsigned int i=0 ; i < m_animations.size() ; i++)
    {
        if (name == m_animations[i].getName())
        {
            m_animations.erase(m_animations.begin()+i);
            return true;
        }
    }
    return false;
}

bool AnimatedSprite::animate(string name, size_t frame)
{
    me::Animation* animation = NULL;
    for (unsigned int i=0 ; i < m_animations.size() ; i++)
    {
        if (name == m_animations[i].getName())
            animation = &m_animations[i];
    }
    if (animation == NULL)
        return false;

    m_currentAnimation = animation;
    m_currentTime.restart();
    m_frozen = false;
    setTexture(*m_currentAnimation->getTexture());
    return true;
}
